<template>
  <div class="app-container" ref="container">
    <!-- 固定的搜索和工具栏容器 -->
    <div class="fixed-header">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="广告语">
            <el-input v-model="formInline.name" placeholder="广告语"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查 询</el-button>
            <el-button @click="resetQuery">重 置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 工具栏 -->
      <div class="toolbar-right">
        <el-button type="primary" size="small" @click="handleAdd">
          <i class="el-icon-plus"></i> 添加广告
        </el-button>
        <el-button size="small" @click="handleRefresh">
          <i class="el-icon-refresh"></i> 刷新
        </el-button>
      </div>
    </div>

    <!-- 表格内容区域 -->
    <div class="table-container">
      <!-- 表格和分页容器 -->
      <div class="content-container">
        <el-table
            ref="table"
            v-loading="loading"
            :data="BannerList"
            border
            style="width: 100%"
        >
          <el-table-column type="selection" width="55"></el-table-column>
          <el-table-column prop="id" label="ID" width="80"></el-table-column>
          <el-table-column prop="name" label="广告语" min-width="200"></el-table-column>
          <!--          图片-->
          <el-table-column prop="picture" label="广告图" width="120">
            <template slot-scope="scope">
              <img :src="scope.row.picture" alt="" style="width: 100px; height: 100px">
            </template>
          </el-table-column>
          <el-table-column prop="url" label="广告地址" width="120"></el-table-column>
          <el-table-column prop="price" label="价格" width="120"></el-table-column>
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button
                  size="mini"
                  type="text"
                  @click="handleEdit(scope.row)"
              >编辑</el-button>
              <el-button
                  size="mini"
                  type="text"
                  @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 新增和修改 -->

        <!-- 分页 -->
        <div class="pagination-container">
          <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="queryParams.pageNo"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="queryParams.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
          >
          </el-pagination>
        </div>
      </div>
    </div>

    <!-- 在表格后面添加对话框组件 -->
    <el-dialog :title="dialogType === 'add' ? '添加广告' : '编辑广告'" :visible.sync="dialogVisible" width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="广告语" prop="name">
          <el-input v-model="form.name" placeholder="请输入广告语"></el-input>
        </el-form-item>
        <el-form-item label="广告图" prop="picture">
          <el-upload
              class="avatar-uploader"
              action="http://localhost:9999/api-tagclass-service/oss/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="form.picture" :src="form.picture" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入广告跳转地址"></el-input>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="form.price" :min="0" :precision="2" :step="0.1"></el-input-number>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: 'Banner',
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      selectedIds: [],
      // 总条数
      total: 0,
      // 表格数据
      BannerList: [],
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
      },
      formInline: {},
      categoryList: [],
      rules: {
        name: [
          { required: true, message: '请输入广告语', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        picture: [
          { required: true, message: '请上传广告图片', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入广告跳转地址', trigger: 'blur' },
          { type: 'url', message: '请输入正确的URL地址', trigger: 'blur' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ]
      },
      dialogVisible: false,
      dialogType: 'add', // 对话框类型：add-新增，edit-编辑
      form: {
        name: '',
        picture: '',
        url: '',
        price: 0
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    /** 查询广告列表 */
    getList() {
      this.axios.post(`http://localhost:9999/api-tagclass-service/banner/findbanner?pageNo=${this.queryParams.pageNo}&pageSize=${this.queryParams.pageSize}`, this.formInline).then(res => {
        this.BannerList = res.data.data.list;
        this.total = res.data.data.total;
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 重置查询表单
      this.formInline = {}
      // 重置分页参数
      this.queryParams = {
        pageNo: 1,
        pageSize: 10
      }
      // 清空选中项（如果有使用表格多选的话）
      if (this.$refs.table) {
        this.$refs.table.clearSelection()
      }
      // 重新加载数据
      this.getList()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.dialogType = 'add'
      this.form = {
        name: '',
        picture: '',
        url: '',
        price: 0
      }
      this.dialogVisible = true
    },
    /** 提交表单 */
    submitForm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.dialogType === 'add') {
            this.addBanner(); // 调用添加方法
          } else {
            this.editBanner(); // 调用编辑方法
          }
        }
      });
    },
    /** 添加广告 */
    addBanner() {
      const url = 'http://localhost:9999/api-tagclass-service/banner/add';
      this.axios.post(url, this.form).then(res => {
        if (res.data) {
          this.$message.success('添加成功');
          this.dialogVisible = false;
          this.getList();
        } else {
          this.$message.error(res.data.msg || '添加失败');
        }
      }).catch(err => {
        console.error(err);
        this.$message.error('添加失败，服务器错误');
      });
    },
    /** 编辑广告 */
    editBanner() {
      const url = 'http://localhost:9999/api-tagclass-service/banner/add'; // 使用相同的 URL
      this.axios.post(url, this.form).then(res => {
        if (res.data) {
          this.$message.success('修改成功');
          this.dialogVisible = false;
          this.getList();
        } else {
          this.$message.error(res.data.msg || '修改失败');
        }
      }).catch(err => {
        console.error(err);
        this.$message.error('修改失败，服务器错误');
      });
    },
    /** 图片上传成功回调 */
    handleAvatarSuccess(res, file) {
      console.log(res); // 打印响应内容以进行调试
      // 假设 res 是上传的图片 URL
      if (res) {
        this.form.picture = res; // 直接将返回的 URL 赋值给 form.picture
        this.$message.success('上传成功');
      } else {
        this.$message.error('上传失败'); // 如果没有返回 URL，则显示失败
      }
    },
    /** 图片上传前的校验 */
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    /** 编辑按钮操作 */
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.form = Object.assign({}, row)
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除广告：' + row.name + '?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        this.axios.post(`http://localhost:9999/api-tagclass-service/banner/delete?id=${row.id}`)
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('删除成功')
                this.getList()
              } else {
                this.$message.error(res.data.msg || '删除失败')
              }
            })
            .catch(() => {
              this.$message.error('删除失败')
            })
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    /** 刷新按钮操作 */
    handleRefresh() {
      this.getList()
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.queryParams.pageSize = val
      this.getList()
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.queryParams.pageNo = val
      this.getList()
    },
  }
}
</script>

<style scoped>
.app-container {
  padding: 0;
  background-color: #fff;
  width: 100%;
  overflow: hidden;
  position: relative;
}

.fixed-header {
  position: fixed;
  top: 50px; /* 与顶部导航栏对齐 */
  left: 210px; /* 与侧边栏对齐 */
  right: 0;
  background-color: #fff;
  z-index: 999;
  padding: 15px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
}

.search-bar {
  flex: 1;
}

.toolbar-right {
  margin-left: 20px;
}

.table-container {
  margin-top: 70px; /* 为固定头部留出空间 */
  padding: 0 20px;
}

.content-container {
  background-color: #fff;
  border-radius: 4px;
  width: 100%;
  overflow-x: hidden;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
  padding: 10px 0;
}

.el-table {
  margin-bottom: 20px;
}

.el-link {
  font-size: 12px;
}

/* 添加全局样式，隐藏滚动条但保持滚动功能 */
::-webkit-scrollbar {
  display: none;
}

/* 调整表单项的间距 */
.demo-form-inline .el-form-item {
  margin-bottom: 0;
  margin-right: 20px;
}

.demo-form-inline .el-form-item:last-child {
  margin-right: 0;
}

.avatar-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>